package com.xjk.encryp;

/**
 * @author 许嘉凯
 */
public class KaisaUtil {


  public static String encrypt(String message, int key) {
    StringBuilder result = new StringBuilder();
    for (char character : message.toCharArray()) {
      if (character != ' ') { // 不移动空格
        int originalAlphabetPosition = character - 'A';
        int newAlphabetPosition = (originalAlphabetPosition + key) % 26;
        char newCharacter = (char) ('A' + newAlphabetPosition);
        result.append(newCharacter);
      } else {
        result.append(character);
      }
    }
    return result.toString();
  }

  public static String decrypt(String message, int key) {
    StringBuilder result = new StringBuilder();
    for (char character : message.toCharArray()) {
      if (character != ' ') { // 不移动空格
        int originalAlphabetPosition = character - 'A';
        int newAlphabetPosition = (originalAlphabetPosition - key) % 26;
        if (newAlphabetPosition < 0) {
          newAlphabetPosition += 26;
        }
        char newCharacter = (char) ('A' + newAlphabetPosition);
        result.append(newCharacter);
      } else {
        result.append(character);
      }
    }
    return result.toString();
  }

  public static void main(String[] args) {

    String message = "HELLO WORLD";
    int shift = 3;

    String encryptedMessage = encrypt(message, shift);
    System.out.println("Encrypted Message: " + encryptedMessage);

    String decryptedMessage = decrypt(encryptedMessage, shift);
    System.out.println("Decrypted Message: " + decryptedMessage);

  }

}
